package com.zhoust.ratelimiter.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * @author 15703
 * @version 1.0
 * @Title
 * @package com.zhoust.ratelimiter.annotation
 * @date 2021/4/21 20:30
 * @desc
 */
@Slf4j
@Aspect
@Component
public class RedisLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    @Pointcut("@annotation(com.zhoust.ratelimiter.annotation.RedisLuaLimiter)")
    public void cut(){
        log.info("开始切入RedisLuaLimiter注解");
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint){

        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        //1. 获取参数
        RedisLuaLimiter redisLuaLimiter = method.getAnnotation(RedisLuaLimiter.class);
        if (redisLuaLimiter == null) {
            return;
        }
        String key = redisLuaLimiter.methodKey();
        Integer limit = redisLuaLimiter.limiter();
        // 如果没设置methodkey, 从调用方法签名生成自动一个key
        if (StringUtils.isBlank(key)) {
            Class[] type = method.getParameterTypes();
            key = method.getClass() + method.getName();

            if (type != null) {
                String paramTypes = Arrays.stream(type)
                        .map(Class::getName)
                        .collect(Collectors.joining(","));
                log.info("param types: " + paramTypes);
                key += "#" + paramTypes;
            }
        }

        //2. 调用redis限流
        boolean acquired = stringRedisTemplate.execute(
            //lua 脚本
            rateLimitLua,
            //lua脚本的key
            Lists.newArrayList(key),
            //Lua脚本Value列表
            limit.toString()
        );

        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.get("");


        if(!acquired){
            log.error("访问量过大，被限流了, key={}", key);
            throw new RuntimeException("访问量过大，被限流了");
        }

    }
}
